<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta name="baidu-site-verification" content="UqlC4pwKIm" />
  <meta name="baidu-site-verification" content="d3U0dGeqGw" />
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="1C1XSuJ8TgM2O0mcZvsgzEdy0IdRZOJfxDYPyh18U9Q" />














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.cat.net/css?family=Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="TX1,OpenCV," />





  <link rel="alternate" href="/atom.xml" title="WordZzzz" type="application/atom+xml" />






<meta name="description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 编者: WordZzzz   &amp;emsp;&amp;emsp;各位看客注意了，本章教程无关硬件平台，在ubuntu下具有通用性，别被标题赶跑了哦。我踩过的坑，您就不要再踩了，枪在手，跟我走。有问题欢迎评论区留言~ &amp;emsp;&amp;em">
<meta name="keywords" content="TX1,OpenCV">
<meta property="og:type" content="article">
<meta property="og:title" content="NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字">
<meta property="og:url" content="http://wordzzzz.gitee.io/2017/10/13/tx-13/index.html">
<meta property="og:site_name" content="WordZzzz">
<meta property="og:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 编者: WordZzzz   &amp;emsp;&amp;emsp;各位看客注意了，本章教程无关硬件平台，在ubuntu下具有通用性，别被标题赶跑了哦。我踩过的坑，您就不要再踩了，枪在手，跟我走。有问题欢迎评论区留言~ &amp;emsp;&amp;em">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-01T07:22:39.224Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字">
<meta name="twitter:description" content="转载请注明作者和出处：http://blog.csdn.net/u011475210 嵌入式平台：NVIDIA Jetson TX1 嵌入式系统：Ubuntu16.04 编者: WordZzzz   &amp;emsp;&amp;emsp;各位看客注意了，本章教程无关硬件平台，在ubuntu下具有通用性，别被标题赶跑了哦。我踩过的坑，您就不要再踩了，枪在手，跟我走。有问题欢迎评论区留言~ &amp;emsp;&amp;em">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://wordzzzz.gitee.io/2017/10/13/tx-13/"/>





  <title>NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字 | WordZzzz</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-111723881-1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?38fde15c2737a3b69622e9dd4f67f6f1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">WordZzzz</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">My Awesome Site</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://wordzzzz.gitee.io/2017/10/13/tx-13/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Word Zzzz">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="WordZzzz">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-13T00:00:00+08:00">
                2017-10-13
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-01-01T15:22:39+08:00">
                2018-01-01
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/TX1/" itemprop="url" rel="index">
                    <span itemprop="name">TX1</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/10/13/tx-13/" class="leancloud_visitors" data-flag-title="NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,471
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  17
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<ul>
<li><strong>转载请注明作者和出处：<a href="http://blog.csdn.net/u011475210" target="_blank" rel="noopener">http://blog.csdn.net/u011475210</a></strong></li>
<li><strong>嵌入式平台：NVIDIA Jetson TX1</strong></li>
<li><strong>嵌入式系统：Ubuntu16.04</strong></li>
<li><strong>编者: WordZzzz</strong></li>
</ul>
<hr>
<p><strong><font color="red" size="4" face="仿宋">&emsp;&emsp;各位看客注意了，本章教程无关硬件平台，在ubuntu下具有通用性，别被标题赶跑了哦。我踩过的坑，您就不要再踩了，枪在手，跟我走。有问题欢迎评论区留言~</font></strong></p>
<p><strong><font color="red" size="4" face="仿宋">&emsp;&emsp;系列教程持续发布中，欢迎订阅、关注、收藏、评论、点赞哦～～(￣▽￣～)～</font></strong></p>
<hr>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>&emsp;&emsp;同样的，由于项目需要，WordZzzz最近尝试在TX1上实现使用Opencv将解析json后得到的信息添加到图片上，其中包括汉字。然而，事情并没我想象的那么简单，主要还是自己对编码格式这块不太熟悉。下面将分两部分进行介绍。</p>
<h2 id="安装freetype"><a href="#安装freetype" class="headerlink" title="安装freetype"></a>安装freetype</h2><p>&emsp;&emsp;首先我们要检查一下自己的系统下面有没有freetype这个软件包：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ pkg-config --cflags --libs freetype2</span><br><span class="line">-I/usr/include/freetype2 -lfreetype</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;如果有上述第二行的打印信息，那么这部分可以跳过，如果没有，就需要按照下面的步骤进行安装了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">#打开终端，添加PPA源:</span><br><span class="line"></span><br><span class="line">$ sudo add-apt-repository ppa:no1wantdthisname/ppa</span><br><span class="line">$ freetype-ppa</span><br><span class="line"></span><br><span class="line">#安装freetype有两种方式：</span><br><span class="line"></span><br><span class="line">$ upgrade freetype</span><br><span class="line"></span><br><span class="line">#或者：</span><br><span class="line"></span><br><span class="line">$ sudo apt update &amp;&amp; sudo apt install libfreetype6</span><br><span class="line"></span><br><span class="line">#如果你想卸载，科一进行如下操作：</span><br><span class="line"></span><br><span class="line">$ sudo apt install ppa-purge &amp;&amp; sudo ppa-purge ppa:no1wantdthisname/ppa</span><br></pre></td></tr></table></figure>
<h2 id="UTF-8与GBK的转换"><a href="#UTF-8与GBK的转换" class="headerlink" title="UTF-8与GBK的转换"></a>UTF-8与GBK的转换</h2><p>ubuntu下系统默认的各种编码格式都是UTF-8，我们想要系统支持GBK，想让程序支持GBK，需要进行如下操作，我采用的方案二。</p>
<h3 id="方案一：iconv函数族"><a href="#方案一：iconv函数族" class="headerlink" title="方案一：iconv函数族"></a>方案一：iconv函数族</h3><p>&emsp;&emsp;iconv函数族的头文件是iconv.h,使用前需包含。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iconv.h&gt;</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;iconv函数族有三个函数,原型如下:</p>
<ul>
<li>(1) iconv_t iconv_open(const char <em>tocode, const char </em>fromcode);<br>此函数说明将要进行哪两种编码的转换,tocode是目标编码,fromcode是原编码,该函数返回一个转换句柄,供以下两个函数使用。</li>
<li>(2) size_t iconv(iconv_t cd,char <strong>inbuf,size_t *inbytesleft,char </strong>outbuf,size_t *outbytesleft);<br>此函数从inbuf中读取字符,转换后输出到outbuf中,inbytesleft用以记录还未转换的字符数,outbytesleft用以记录输出缓冲的剩余空间。</li>
<li>(3) int iconv_close(iconv_t cd);<br>此函数用于关闭转换句柄,释放资源。</li>
</ul>
<p>&emsp;&emsp;实现代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iconv.h&gt;  </span><br><span class="line">#include &lt;stdlib.h&gt;  </span><br><span class="line">#include &lt;stdio.h&gt;  </span><br><span class="line">#include &lt;unistd.h&gt;  </span><br><span class="line">#include &lt;fcntl.h&gt;  </span><br><span class="line">#include &lt;string.h&gt;  </span><br><span class="line">#include &lt;sys/stat.h&gt;  </span><br><span class="line">  </span><br><span class="line">int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen,  </span><br><span class="line">        char *outbuf, size_t outlen) &#123;  </span><br><span class="line">    iconv_t cd;  </span><br><span class="line">    char **pin = &amp;inbuf;  </span><br><span class="line">    char **pout = &amp;outbuf;  </span><br><span class="line">  </span><br><span class="line">    cd = iconv_open(to_charset, from_charset);  </span><br><span class="line">    if (cd == 0)  </span><br><span class="line">        return -1;  </span><br><span class="line">    memset(outbuf, 0, outlen);  </span><br><span class="line">    if (iconv(cd, pin, &amp;inlen, pout, &amp;outlen) == -1)  </span><br><span class="line">        return -1;  </span><br><span class="line">    iconv_close(cd);  </span><br><span class="line">    *pout = &apos;\0&apos;;  </span><br><span class="line">  </span><br><span class="line">    return 0;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) &#123;  </span><br><span class="line">    return code_convert(&quot;utf-8&quot;, &quot;gb2312&quot;, inbuf, inlen, outbuf, outlen);  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) &#123;  </span><br><span class="line">    return code_convert(&quot;gb2312&quot;, &quot;utf-8&quot;, inbuf, inlen, outbuf, outlen);  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">int main(void) &#123;  </span><br><span class="line">    char *s = &quot;中国&quot;;  </span><br><span class="line">    int fd = open(&quot;test.txt&quot;, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);  </span><br><span class="line">    char buf[10];  </span><br><span class="line">    u2g(s, strlen(s), buf, sizeof(buf));  </span><br><span class="line">    write(fd, buf, strlen(buf));  </span><br><span class="line">    close(fd);  </span><br><span class="line">  </span><br><span class="line">    fd = open(&quot;test.txt2&quot;, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);  </span><br><span class="line">    char buf2[10];  </span><br><span class="line">    g2u(buf, strlen(buf), buf2, sizeof(buf2));  </span><br><span class="line">    write(fd, buf2, strlen(buf2));  </span><br><span class="line">    close(fd);  </span><br><span class="line">    return 1;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="方案二：使用mbstowcs和wcstombs"><a href="#方案二：使用mbstowcs和wcstombs" class="headerlink" title="方案二：使用mbstowcs和wcstombs"></a>方案二：使用mbstowcs和wcstombs</h3><p>&emsp;&emsp;mbstowcs将多字节编码转换为宽字节编码；wcstombs将宽字节编码转换为多字节编码<br>注意，需要系统编码的支持，可以通过locale -a 查看系统支持的。若不支持zh_CN.gbk, 需要安装，在ubuntu上的安装步骤如下：</p>
<p>&emsp;&emsp;编辑配置文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$sudo vim /var/lib/locales/supported.d/zh-hans</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;加入下面几行代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">zh_CN.UTF-8 UTF-8</span><br><span class="line">zh_SG.UTF-8 UTF-8</span><br><span class="line">zh_CN.GBK GBK</span><br><span class="line">zh_CN.GB18030 GB18030</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;保存后更新：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ sudo locale-gen</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;查看:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$ locale -a</span><br><span class="line">C</span><br><span class="line">POSIX</span><br><span class="line">···</span><br><span class="line">zh_CN.gb18030</span><br><span class="line">zh_CN.gbk</span><br><span class="line">zh_CN.utf8</span><br><span class="line">zh_SG.utf8</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;测试代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdlib.h&gt;  </span><br><span class="line">#include &lt;stdio.h&gt;  </span><br><span class="line">#include &lt;string.h&gt;  </span><br><span class="line">#include &lt;unistd.h&gt;  </span><br><span class="line">#include &lt;fcntl.h&gt;  </span><br><span class="line">#include &lt;sys/stat.h&gt;  </span><br><span class="line">#include &lt;locale.h&gt;  </span><br><span class="line">  </span><br><span class="line">/** </span><br><span class="line"> * DESCRIPTION: 实现由utf8编码到gbk编码的转换 </span><br><span class="line"> * </span><br><span class="line"> * Input: gbkStr,转换后的字符串;  srcStr,待转换的字符串; maxGbkStrlen, gbkStr的最 </span><br><span class="line"> 大长度 </span><br><span class="line"> * Output: gbkStr </span><br><span class="line"> * Returns: -1,fail;&gt;0,success </span><br><span class="line"> * </span><br><span class="line"> */  </span><br><span class="line">int utf82gbk(char *gbkStr, const char *srcStr, int maxGbkStrlen) &#123;  </span><br><span class="line">    if (NULL == srcStr) &#123;  </span><br><span class="line">        printf(&quot;Bad Parameter：srcStr\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    //首先先将utf8编码转换为unicode编码  </span><br><span class="line">    if (NULL == setlocale(LC_ALL, &quot;zh_CN.utf8&quot;)) //设置转换为unicode前的码,当前为utf8编码  </span><br><span class="line">            &#123;  </span><br><span class="line">        printf(&quot;Bad Parameter：zh_CN.utf8\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    int unicodeLen = mbstowcs(NULL, srcStr, 0); //计算转换后的长度  </span><br><span class="line">    if (unicodeLen &lt;= 0) &#123;  </span><br><span class="line">        printf(&quot;Can not Transfer!!!\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125;  </span><br><span class="line">    wchar_t *unicodeStr = (wchar_t *) calloc(sizeof(wchar_t), unicodeLen + 1);  </span><br><span class="line">    mbstowcs(unicodeStr, srcStr, strlen(srcStr)); //将utf8转换为unicode  </span><br><span class="line">  </span><br><span class="line">    //将unicode编码转换为gbk编码  </span><br><span class="line">    if (NULL == setlocale(LC_ALL, &quot;zh_CN.gbk&quot;)) //设置unicode转换后的码,当前为gbk  </span><br><span class="line">            &#123;  </span><br><span class="line">        printf(&quot;Bad Parameter：zh_CN.gbk\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125;  </span><br><span class="line">    int gbkLen = wcstombs(NULL, unicodeStr, 0); //计算转换后的长度  </span><br><span class="line">    if (gbkLen &lt;= 0) &#123;  </span><br><span class="line">        printf(&quot;Can not Transfer!!!\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125; else if (gbkLen &gt;= maxGbkStrlen) //判断空间是否足够  </span><br><span class="line">            &#123;  </span><br><span class="line">        printf(&quot;Dst Str memory not enough\n&quot;);  </span><br><span class="line">        return -1;  </span><br><span class="line">    &#125;  </span><br><span class="line">    wcstombs(gbkStr, unicodeStr, gbkLen);  </span><br><span class="line">    gbkStr[gbkLen] = 0; //添加结束符  </span><br><span class="line">    free(unicodeStr);  </span><br><span class="line">    return gbkLen;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">int main(void) &#123;  </span><br><span class="line">    char *s = &quot;我爱WordZzzz&quot;;  </span><br><span class="line">    int fd = open(&quot;test.txt&quot;, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);  </span><br><span class="line">    char buf[10];  </span><br><span class="line">    utf82gbk(buf, s, sizeof(buf));  </span><br><span class="line">    write(fd, buf, strlen(buf));  </span><br><span class="line">    close(fd);  </span><br><span class="line">  </span><br><span class="line">    return 1;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="OpenCV的中文支持"><a href="#OpenCV的中文支持" class="headerlink" title="OpenCV的中文支持"></a>OpenCV的中文支持</h2><p>&emsp;&emsp;OpenCV想要支持中文显示，需要添加额外的文件。网上参考的都是这两个文件，2007年的，历史悠久。</p>
<p>&emsp;&emsp;头文件CvxText.h：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br></pre></td><td class="code"><pre><span class="line">#ifndef OPENCV_CVX_TEXT_2007_08_31_H</span><br><span class="line">#define OPENCV_CVX_TEXT_2007_08_31_H</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line">* \file CvxText.h</span><br><span class="line">* \brief OpenCV汉字输出接口</span><br><span class="line">*</span><br><span class="line">* 实现了汉字输出功能。</span><br><span class="line">*/</span><br><span class="line"></span><br><span class="line">#include &lt;ft2build.h&gt;</span><br><span class="line">#include FT_FREETYPE_H</span><br><span class="line"></span><br><span class="line">#include&lt;opencv2/opencv.hpp&gt;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line">* \class CvxText</span><br><span class="line">* \brief OpenCV中输出汉字</span><br><span class="line">*</span><br><span class="line">* OpenCV中输出汉字。字库提取采用了开源的FreeFype库。由于FreeFype是</span><br><span class="line">* GPL版权发布的库，和OpenCV版权并不一致，因此目前还没有合并到OpenCV</span><br><span class="line">* 扩展库中。</span><br><span class="line">*</span><br><span class="line">* 显示汉字的时候需要一个汉字字库文件，字库文件系统一般都自带了。</span><br><span class="line">* 这里采用的是一个开源的字库：“文泉驿正黑体”。</span><br><span class="line">*</span><br><span class="line">* 关于&quot;OpenCV扩展库&quot;的细节请访问</span><br><span class="line">* http://code.google.com/p/opencv-extension-library/</span><br><span class="line">*</span><br><span class="line">* 关于FreeType的细节请访问</span><br><span class="line">* http://www.freetype.org/</span><br><span class="line">*/</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class CvxText</span><br><span class="line">&#123;</span><br><span class="line">	// 禁止copy</span><br><span class="line"></span><br><span class="line">	CvxText&amp; operator=(const CvxText&amp;);</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">public:</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 装载字库文件</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	CvxText(const char *freeType);</span><br><span class="line">	virtual ~CvxText();</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 获取字体。目前有些参数尚不支持。</span><br><span class="line">	*</span><br><span class="line">	* \param font        字体类型, 目前不支持</span><br><span class="line">	* \param size        字体大小/空白比例/间隔比例/旋转角度</span><br><span class="line">	* \param underline   下画线</span><br><span class="line">	* \param diaphaneity 透明度</span><br><span class="line">	*</span><br><span class="line">	* \sa setFont, restoreFont</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	void getFont(int *type,</span><br><span class="line">		CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL);</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 设置字体。目前有些参数尚不支持。</span><br><span class="line">	*</span><br><span class="line">	* \param font        字体类型, 目前不支持</span><br><span class="line">	* \param size        字体大小/空白比例/间隔比例/旋转角度</span><br><span class="line">	* \param underline   下画线</span><br><span class="line">	* \param diaphaneity 透明度</span><br><span class="line">	*</span><br><span class="line">	* \sa getFont, restoreFont</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	void setFont(int *type,</span><br><span class="line">		CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL);</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 恢复原始的字体设置。</span><br><span class="line">	*</span><br><span class="line">	* \sa getFont, setFont</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	void restoreFont();</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。</span><br><span class="line">	*</span><br><span class="line">	* \param img  输出的影象</span><br><span class="line">	* \param text 文本内容</span><br><span class="line">	* \param pos  文本位置</span><br><span class="line">	*</span><br><span class="line">	* \return 返回成功输出的字符长度，失败返回-1。</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	int putText(IplImage *img, const char    *text, CvPoint pos);</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。</span><br><span class="line">	*</span><br><span class="line">	* \param img  输出的影象</span><br><span class="line">	* \param text 文本内容</span><br><span class="line">	* \param pos  文本位置</span><br><span class="line">	*</span><br><span class="line">	* \return 返回成功输出的字符长度，失败返回-1。</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	int putText(IplImage *img, const wchar_t *text, CvPoint pos);</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 输出汉字。遇到不能输出的字符将停止。</span><br><span class="line">	*</span><br><span class="line">	* \param img   输出的影象</span><br><span class="line">	* \param text  文本内容</span><br><span class="line">	* \param pos   文本位置</span><br><span class="line">	* \param color 文本颜色</span><br><span class="line">	*</span><br><span class="line">	* \return 返回成功输出的字符长度，失败返回-1。</span><br><span class="line">	*/</span><br><span class="line"></span><br><span class="line">	int putText(IplImage *img, const char    *text, CvPoint pos, CvScalar color);</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	* 输出汉字。遇到不能输出的字符将停止。</span><br><span class="line">	*</span><br><span class="line">	* \param img   输出的影象</span><br><span class="line">	* \param text  文本内容</span><br><span class="line">	* \param pos   文本位置</span><br><span class="line">	* \param color 文本颜色</span><br><span class="line">	*</span><br><span class="line">	* \return 返回成功输出的字符长度，失败返回-1。</span><br><span class="line">	*/</span><br><span class="line">	int putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color);</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">private:</span><br><span class="line"></span><br><span class="line">	// 输出当前字符, 更新m_pos位置</span><br><span class="line"></span><br><span class="line">	void putWChar(IplImage *img, wchar_t wc, CvPoint &amp;pos, CvScalar color);</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">private:</span><br><span class="line"></span><br><span class="line">	FT_Library   m_library;   // 字库</span><br><span class="line">	FT_Face      m_face;      // 字体</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line"></span><br><span class="line">	// 默认的字体输出参数</span><br><span class="line"></span><br><span class="line">	int         m_fontType;</span><br><span class="line">	CvScalar   m_fontSize;</span><br><span class="line">	bool      m_fontUnderline;</span><br><span class="line">	float      m_fontDiaphaneity;</span><br><span class="line"></span><br><span class="line">	//================================================================</span><br><span class="line">	//================================================================</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">#endif // OPENCV_CVX_TEXT_2007_08_31_H</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;源文件cvText.cpp：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br></pre></td><td class="code"><pre><span class="line">/*</span><br><span class="line"> * cvText.cpp</span><br><span class="line"> *</span><br><span class="line"> *  Created on: Sep 20, 2017</span><br><span class="line"> *      Author: wordzzzz</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">#include &lt;wchar.h&gt;</span><br><span class="line">#include &lt;assert.h&gt;</span><br><span class="line">#include &lt;locale.h&gt;</span><br><span class="line">#include &lt;ctype.h&gt;</span><br><span class="line"></span><br><span class="line">#include &quot;CvxText.h&quot;</span><br><span class="line"></span><br><span class="line">//====================================================================</span><br><span class="line">//====================================================================</span><br><span class="line"></span><br><span class="line">// 打开字库</span><br><span class="line"></span><br><span class="line">CvxText::CvxText(const char *freeType)</span><br><span class="line">&#123;</span><br><span class="line">	assert(freeType != NULL);</span><br><span class="line"></span><br><span class="line">	// 打开字库文件, 创建一个字体</span><br><span class="line"></span><br><span class="line">	if (FT_Init_FreeType(&amp;m_library)) throw;</span><br><span class="line">	if (FT_New_Face(m_library, freeType, 0, &amp;m_face)) throw;</span><br><span class="line"></span><br><span class="line">	// 设置字体输出参数</span><br><span class="line"></span><br><span class="line">	restoreFont();</span><br><span class="line"></span><br><span class="line">	// 设置C语言的字符集环境</span><br><span class="line"></span><br><span class="line">	setlocale(LC_ALL, &quot;&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 释放FreeType资源</span><br><span class="line"></span><br><span class="line">CvxText::~CvxText()</span><br><span class="line">&#123;</span><br><span class="line">	FT_Done_Face(m_face);</span><br><span class="line">	FT_Done_FreeType(m_library);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 设置字体参数:</span><br><span class="line">//</span><br><span class="line">// font         - 字体类型, 目前不支持</span><br><span class="line">// size         - 字体大小/空白比例/间隔比例/旋转角度</span><br><span class="line">// underline   - 下画线</span><br><span class="line">// diaphaneity   - 透明度</span><br><span class="line"></span><br><span class="line">void CvxText::getFont(int *type, CvScalar *size, bool *underline, float *diaphaneity)</span><br><span class="line">&#123;</span><br><span class="line">	if (type) *type = m_fontType;</span><br><span class="line">	if (size) *size = m_fontSize;</span><br><span class="line">	if (underline) *underline = m_fontUnderline;</span><br><span class="line">	if (diaphaneity) *diaphaneity = m_fontDiaphaneity;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">void CvxText::setFont(int *type, CvScalar *size, bool *underline, float *diaphaneity)</span><br><span class="line">&#123;</span><br><span class="line">	// 参数合法性检查</span><br><span class="line"></span><br><span class="line">	if (type)</span><br><span class="line">	&#123;</span><br><span class="line">		if (type &gt;= 0) m_fontType = *type;</span><br><span class="line">	&#125;</span><br><span class="line">	if (size)</span><br><span class="line">	&#123;</span><br><span class="line">		m_fontSize.val[0] = fabs(size-&gt;val[0]);</span><br><span class="line">		m_fontSize.val[1] = fabs(size-&gt;val[1]);</span><br><span class="line">		m_fontSize.val[2] = fabs(size-&gt;val[2]);</span><br><span class="line">		m_fontSize.val[3] = fabs(size-&gt;val[3]);</span><br><span class="line">	&#125;</span><br><span class="line">	if (underline)</span><br><span class="line">	&#123;</span><br><span class="line">		m_fontUnderline = *underline;</span><br><span class="line">	&#125;</span><br><span class="line">	if (diaphaneity)</span><br><span class="line">	&#123;</span><br><span class="line">		m_fontDiaphaneity = *diaphaneity;</span><br><span class="line">	&#125;</span><br><span class="line">	//FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 恢复原始的字体设置</span><br><span class="line"></span><br><span class="line">void CvxText::restoreFont()</span><br><span class="line">&#123;</span><br><span class="line">	m_fontType = 0;            // 字体类型(不支持)</span><br><span class="line"></span><br><span class="line">	m_fontSize.val[0] = 20;      // 字体大小</span><br><span class="line">	m_fontSize.val[1] = 0.5;   // 空白字符大小比例</span><br><span class="line">	m_fontSize.val[2] = 0.1;   // 间隔大小比例</span><br><span class="line">	m_fontSize.val[3] = 0;      // 旋转角度(不支持)</span><br><span class="line"></span><br><span class="line">	m_fontUnderline = false;   // 下画线(不支持)</span><br><span class="line"></span><br><span class="line">	m_fontDiaphaneity = 1.0;   // 色彩比例(可产生透明效果)</span><br><span class="line"></span><br><span class="line">	// 设置字符大小</span><br><span class="line"></span><br><span class="line">	FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 输出函数(颜色默认为黑色)</span><br><span class="line"></span><br><span class="line">int CvxText::putText(IplImage *img, const char    *text, CvPoint pos)</span><br><span class="line">&#123;</span><br><span class="line">	return putText(img, text, pos, CV_RGB(255, 255, 255));</span><br><span class="line">&#125;</span><br><span class="line">int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos)</span><br><span class="line">&#123;</span><br><span class="line">	return putText(img, text, pos, CV_RGB(255, 255, 255));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//</span><br><span class="line"></span><br><span class="line">int CvxText::putText(IplImage *img, const char    *text, CvPoint pos, CvScalar color)</span><br><span class="line">&#123;</span><br><span class="line">	if (img == NULL) return -1;</span><br><span class="line">	if (text == NULL) return -1;</span><br><span class="line"></span><br><span class="line">	//</span><br><span class="line"></span><br><span class="line">	int i;</span><br><span class="line">	for (i = 0; text[i] != &apos;\0&apos;; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		wchar_t wc = text[i];</span><br><span class="line"></span><br><span class="line">		// 解析双字节符号</span><br><span class="line"></span><br><span class="line">		if (!isascii(wc)) mbtowc(&amp;wc, &amp;text[i++], 2);</span><br><span class="line"></span><br><span class="line">		// 输出当前的字符</span><br><span class="line"></span><br><span class="line">		putWChar(img, wc, pos, color);</span><br><span class="line">	&#125;</span><br><span class="line">	return i;</span><br><span class="line">&#125;</span><br><span class="line">int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color)</span><br><span class="line">&#123;</span><br><span class="line">	if (img == NULL) return -1;</span><br><span class="line">	if (text == NULL) return -1;</span><br><span class="line"></span><br><span class="line">	//</span><br><span class="line"></span><br><span class="line">	int i;</span><br><span class="line">	for (i = 0; text[i] != &apos;\0&apos;; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		// 输出当前的字符</span><br><span class="line"></span><br><span class="line">		putWChar(img, text[i], pos, color);</span><br><span class="line">	&#125;</span><br><span class="line">	return i;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 输出当前字符, 更新m_pos位置</span><br><span class="line"></span><br><span class="line">void CvxText::putWChar(IplImage *img, wchar_t wc, CvPoint &amp;pos, CvScalar color)</span><br><span class="line">&#123;</span><br><span class="line">	// 根据unicode生成字体的二值位图</span><br><span class="line"></span><br><span class="line">	FT_UInt glyph_index = FT_Get_Char_Index(m_face, wc);</span><br><span class="line">	FT_Load_Glyph(m_face, glyph_index, FT_LOAD_DEFAULT);</span><br><span class="line">	FT_Render_Glyph(m_face-&gt;glyph, FT_RENDER_MODE_MONO);</span><br><span class="line"></span><br><span class="line">	//</span><br><span class="line"></span><br><span class="line">	FT_GlyphSlot slot = m_face-&gt;glyph;</span><br><span class="line"></span><br><span class="line">	// 行列数</span><br><span class="line"></span><br><span class="line">	int rows = slot-&gt;bitmap.rows;</span><br><span class="line">	int cols = slot-&gt;bitmap.width;</span><br><span class="line"></span><br><span class="line">	//</span><br><span class="line"></span><br><span class="line">	for (int i = 0; i &lt; rows; ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		for (int j = 0; j &lt; cols; ++j)</span><br><span class="line">		&#123;</span><br><span class="line">			int off = ((img-&gt;origin == 0) ? i : (rows - 1 - i))</span><br><span class="line">				* slot-&gt;bitmap.pitch + j / 8;</span><br><span class="line"></span><br><span class="line">			if (slot-&gt;bitmap.buffer[off] &amp; (0xC0 &gt;&gt; (j % 8)))</span><br><span class="line">			&#123;</span><br><span class="line">				int r = (img-&gt;origin == 0) ? pos.y - (rows - 1 - i) : pos.y + i;;</span><br><span class="line">				int c = pos.x + j;</span><br><span class="line"></span><br><span class="line">				if (r &gt;= 0 &amp;&amp; r &lt; img-&gt;height</span><br><span class="line">					&amp;&amp; c &gt;= 0 &amp;&amp; c &lt; img-&gt;width)</span><br><span class="line">				&#123;</span><br><span class="line">					CvScalar scalar = cvGet2D(img, r, c);</span><br><span class="line"></span><br><span class="line">					// 进行色彩融合</span><br><span class="line"></span><br><span class="line">					float p = m_fontDiaphaneity;</span><br><span class="line">					for (int k = 0; k &lt; 4; ++k)</span><br><span class="line">					&#123;</span><br><span class="line">						scalar.val[k] = scalar.val[k] * (1 - p) + color.val[k] * p;</span><br><span class="line">					&#125;</span><br><span class="line"></span><br><span class="line">					cvSet2D(img, r, c, scalar);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; // end for</span><br><span class="line">	&#125; // end for</span><br><span class="line"></span><br><span class="line">	// 修改下一个字的输出位置</span><br><span class="line"></span><br><span class="line">	double space = m_fontSize.val[0] * m_fontSize.val[1];</span><br><span class="line">	double sep = m_fontSize.val[0] * m_fontSize.val[2];</span><br><span class="line"></span><br><span class="line">	pos.x += (int)((cols ? cols : space) + sep);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;测试代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;opencv/highgui.h&gt;  </span><br><span class="line">#include &lt;assert.h&gt;  </span><br><span class="line">#include &quot;CvxText.h&quot;  </span><br><span class="line">using namespace cv;  </span><br><span class="line">  </span><br><span class="line">int main(int argc, char *argv[])  </span><br><span class="line">&#123;  </span><br><span class="line">    // 打开一幅  </span><br><span class="line">    IplImage *img = cvLoadImage(&quot;lena.jpg&quot;);  </span><br><span class="line">    // 输出汉字  </span><br><span class="line">    &#123;  </span><br><span class="line">        CvxText text(&quot;simhei.ttf&quot;); // &quot;zenhei.ttf&quot;为黑体常规  </span><br><span class="line">        const char *msg = &quot;在OpenCV中输出汉字！&quot;;  </span><br><span class="line">        float p = 0.5;  </span><br><span class="line">        text.setFont(NULL, NULL, NULL, &amp;p);   // 透明处理  </span><br><span class="line">        text.putText(img, msg, cvPoint(100, 150), CV_RGB(255, 0, 0));  </span><br><span class="line">    &#125;  </span><br><span class="line">    // 定义窗口，并显示影象  </span><br><span class="line">    cvShowImage(&quot;test&quot;, img); cvWaitKey(-1);  </span><br><span class="line">    cvReleaseImage(&amp;img);  </span><br><span class="line">    return 0;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;代码里面的simhei.tff是字体名称，需要拷贝到你程序的执行目录下，当然也可以直接在代码中写字体的路径。window下一般都有这个字体，ubuntu的话，来windows下拷贝一下就好，windows的的字体目录：C:\Windows\Fonts。</p>
<h2 id="敲重点"><a href="#敲重点" class="headerlink" title="敲重点"></a>敲重点</h2><p><strong><font color="red" size="4" face="仿宋">&emsp;&emsp;如果你的代码的编码格式本身就是GBK，那么你就不需要UTF-8转GBK这个过程，即第二个部分就可以略过；但是，如果你进行第三部分的时候，发现部分汉字能显示，部分不能显示，那就是编码问题，需要调用第二部分的UTF-8转GBK的函数。/font&gt;</font></strong></p>
<hr>
<p><strong><font color="red" size="3" face="仿宋">系列教程持续发布中，欢迎订阅、关注、收藏、评论、点赞哦～～(￣▽￣～)～</font></strong></p>
<p><strong><font color="red" size="3" face="仿宋">完的汪(∪｡∪)｡｡｡zzz</font></strong></p>
<hr>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Word Zzzz
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://wordzzzz.gitee.io/2017/10/13/tx-13/" title="NVIDIA Jetson TX1 系列开发教程之十三：使用OpenCV在图像上添加汉字">http://wordzzzz.gitee.io/2017/10/13/tx-13/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/TX1/" rel="tag"># TX1</a>
          
            <a href="/tags/OpenCV/" rel="tag"># OpenCV</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/12/tx-12/" rel="next" title="NVIDIA Jetson TX1 系列开发教程之十二：libcurl、RapidJSON安装">
                <i class="fa fa-chevron-left"></i> NVIDIA Jetson TX1 系列开发教程之十二：libcurl、RapidJSON安装
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/14/tx-14/" rel="prev" title="NVIDIA Jetson TX1 系列开发教程之十四：YOLO安装与优化加速">
                NVIDIA Jetson TX1 系列开发教程之十四：YOLO安装与优化加速 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjgzNi85Mzk3"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Word Zzzz" />
            
              <p class="site-author-name" itemprop="name">Word Zzzz</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

			<!--my custom code begin-->
			<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js"></script>
			<script type="text/javascript">
			  $("#sidebar").hover(function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 1});
			  },function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 0});
			  });
			</script>
			<div id="mydivshow" class="mydivshow">
			<!--my custom code end-->
			
          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">155</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/wordzzzz" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/wordzzzz" target="_blank" title="Gitee">
                    
                      <i class="fa fa-fw fa-glide"></i>Gitee</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:wordzzzzgm@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://plus.google.com/" target="_blank" title="Google">
                    
                      <i class="fa fa-fw fa-google"></i>Google</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.weibo.com/u/3191972527?from=107C295010&wm=20005_0002&sourceType=weixin&uid=3191972527&is_all=1" target="_blank" title="微博">
                    
                      <i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wordzzzz" target="_blank" title="知乎">
                    
                      <i class="fa fa-fw fa-bell"></i>知乎</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/u011475210" title="CSDN博客主页" target="_blank">CSDN博客主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.gitee.io" title="中国站主页" target="_blank">中国站主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.github.io" title="全球站主页" target="_blank">全球站主页</a>
                  </li>
                
              </ul>
            </div>
          

          <div id="player1" class="aplayer"></div>
<script src="/js/src/APlayer.min.js"></script>
<script type="text/javascript">
var ap = new APlayer({
    element: document.getElementById('player1'),                       // Optional, player element
    narrow: false,                                                     // Optional, narrow style
    autoplay: false,                                                    // Optional, autoplay song(s), not supported by mobile browsers
    showlrc: 0,                                                        // Optional, show lrc, can be 0, 1, 2, see: ###With lrc
    mutex: true,                                                       // Optional, pause other players when this player playing
    theme: '#e6d0b2',                                                  // Optional, theme color, default: #b7daff
    mode: 'random',                                                    // Optional, play mode, can be `random` `single` `circulation`(loop) `order`(no loop), default: `circulation`
    preload: 'metadata',                                               // Optional, the way to load music, can be 'none' 'metadata' 'auto', default: 'auto'
    listmaxheight: '513px',                                             // Optional, max height of play list
    music: {                                                           // Required, music info, see: ###With playlist
        title: '你曾是少年',                                          // Required, music title
        author: 'cover',                          // Required, music author
        url: 'http://mp3.qqmusic.cc/yq/102426570.mp3',  // Required, music url
        pic: '/images/visitor.jpg',  // Optional, music picture
    }
});
</script>
        </div>
		<!--my custom code begin-->
		</div>
		<!--my custom code end-->
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装freetype"><span class="nav-number">2.</span> <span class="nav-text">安装freetype</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UTF-8与GBK的转换"><span class="nav-number">3.</span> <span class="nav-text">UTF-8与GBK的转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方案一：iconv函数族"><span class="nav-number">3.1.</span> <span class="nav-text">方案一：iconv函数族</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方案二：使用mbstowcs和wcstombs"><span class="nav-number">3.2.</span> <span class="nav-text">方案二：使用mbstowcs和wcstombs</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#OpenCV的中文支持"><span class="nav-number">4.</span> <span class="nav-text">OpenCV的中文支持</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#敲重点"><span class="nav-number">5.</span> <span class="nav-text">敲重点</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Word Zzzz</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">176.8k</span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>




  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("tnjOBN3eibs4dfP2s8dFMF8s-gzGzoHsz", "tDaBF4vRsSyaeSk9vKOOow6E");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  <script src="/js/src/Aplayer-Controler.js"></script>
<div id="AP-controler"></div>
<script type="text/javascript">
var myapc=new APlayer_Controler({
		APC_dom:$('#AP-controler'),
		aplayer:ap, //此为绑定的aplayer对象
		attach_right:false,
		position:{top:'300px',bottom:''},
		fixed:true,
		btn_width:100,
		btn_height:120,
		img_src:['http://oty1v077k.bkt.clouddn.com/bukagirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/jumpgirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/pentigirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/%E8%90%8C1.gif'],
		img_style:{repeat:'no-repeat',position:'center',size:'contain'},
		ctrls_color:'rgba(173,255,47,0.8)',
		ctrls_hover_color:'rgba(255,140,0,0.7)',
		tips_on:true,
		tips_width:140,
		tips_height:25,
		tips_color:'rgba(255,255,255,0.6)',
		tips_content:{},
		timeout:30
	});
</script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>



</body>
</html>
